<?php
namespace common\services\upload;

use common\models\Common;
use Qiniu\Auth;
use Qiniu\Storage\BucketManager;
use Qiniu\Storage\UploadManager;
use Yii;
use yii\base\Exception;
use yii\web\UploadedFile;

class Qiniu extends Common
{
        #q6lx8nqef.bkt.clouddn.com
    private $_bucket = '';
    private $_accessKey = '';
    private $_secretKey = '';
    private $_transCodeQueue = 'jiuqiu_transcode';
    protected $auth;


    const TRANS_CODE_URL_LEARN = 1;
    //转码之后才需要回调地址
    const NOTIFY_URL = [
        self::TRANS_CODE_URL_LEARN => '',
    ];

    public function init() {
        parent::init();
        $this->_accessKey   = Yii::$app->params['QINIU_ACCESS_KEY'];
        $this->_secretKey   = Yii::$app->params['QINIU_SECRET_KEY'];
        $this->_bucket      = Yii::$app->params['QINIU_BUCKET'];
        $this->_transCodeQueue = Yii::$app->params['QINIU_TRANS_CODE_QUEUE'];
        $this->auth = new Auth($this->_accessKey, $this->_secretKey);
    }
    /**
     * 上传文件 使用七牛云上传文件
     * @param string $prefix
     * @param string $field
     * @param string $oldKey
     * @return bool
     */
    public function uploadFile($prefix = 'default', $field = 'file', $oldKey = '') {
        $fileObject = UploadedFile::getInstanceByName($field);
        $ext = $fileObject->getExtension();

        #获取临时文件名
        $fileName = $fileObject->tempName;
        #生成文件名
        $key = md5(time() . rand(10000, 99999));
        #获取验证信息
        $auth = $this->auth;
        $policy = null;
        #获取上传token
        $upToken = $auth->uploadToken($this->_bucket, null, 3600, $policy, true);

        $upManager = new UploadManager();
        //上传到七牛后保存的文件名
        $uploadFileName = $prefix.'/'.$key.'.'.$ext;
        // 要上传文件的本地路径
        list($ret, $error) = $upManager->putFile($upToken, $uploadFileName, $fileName);
        if ($error != null) {
            return false;
        }
        //如果存在则先删除
        if ($oldKey) {
            $this->deleteOldKey($oldKey);
        }
        return $ret['key'];
    }

    /**
     * 上传文件 使用七牛云上传文件
     * @param string $prefix
     * @param string $field
     * @param string $oldKey
     * @return bool
     */
    public function uploadLocalFile($prefix = 'default', $path = '', $key = '') {
        #生成文件名
        $auth = $this->auth;
        $policy = null;
        #获取上传token
        $upToken = $auth->uploadToken($this->_bucket, null, 3600, $policy, true);

        $upManager = new UploadManager();
        if (empty($key)) {
            $key = date("ymdhis") . rand(1000, 2999);
        }
        //上传到七牛后保存的文件名
        $uploadFileName = $prefix.'/'.$key.'.jpg';
        // 要上传文件的本地路径
        list($ret, $error) = $upManager->putFile($upToken, $uploadFileName, $path);
        if ($error != null) {
            return false;
        }
        return $ret['key'];
    }

    /**
     * 多重上传文件 使用七牛云上传文件
     * @param string $prefix
     * @param string $field
     *
     * @return array
     */
    public function uploadFileMultiple($prefix = 'default', $field = 'file') {
        $fileObject = UploadedFile::getInstancesByName($field);
        file_put_contents("/tmp/up.txt", print_r($fileObject, true), FILE_APPEND);
        $paths = [];
        foreach ($fileObject as $image) {
            if (!empty($image)) {
                //不为空则上传了新图片，需要删除就图片
                file_put_contents("/tmp/up.txt", print_r($image, true), FILE_APPEND);
                $fileName = $image->tempName;
                //获取上传图片后缀名
                $ext = $image->getExtension();
                file_put_contents("/tmp/up.txt", '后缀:', FILE_APPEND);
                file_put_contents("/tmp/up.txt", print_r($ext, true), FILE_APPEND);
                file_put_contents("/tmp/up.txt", '=====结束======', FILE_APPEND);

                $key = md5(time() . rand(10000, 99999));
                $auth = $this->auth;
                $policy = null;
                $upToken = $auth->uploadToken($this->_bucket, null, 3600, $policy, true);

                $upManager = new UploadManager();
                //上传到七牛后保存的文件名
                $uploadFileName = $prefix.'/'. $key . '.'. $ext;

                // 要上传文件的本地路径
//                $res = $upManager->putFile($upToken, $uploadFileName, $fileName);

                list($ret, $error) = $upManager->putFile($upToken, $uploadFileName, $fileName);
                if ($error != null) {
                    continue;
                }

                $paths[] = $ret['key'];
            }
        }
        return $paths;
    }
    /**
     * 七牛上传二进制流文件
     * @param string $prefix
     * @param string $data
     * @return bool
     */
    public function put($prefix = 'default',$data = '') {
        $key = md5(time() . rand(10000, 99999));
        $ext = 'png';
        $auth = $this->auth;
        $policy = null;
        $upToken = $auth->uploadToken($this->_bucket, null, 3600, $policy, true);
        $upManager = new UploadManager();
        //上传到七牛后保存的文件名
        $key =  $prefix.'/'.$key.'.'.$ext;
        // 要上传文件的本地路径
        list($ret, $error) = $upManager->put($upToken, $key, $data);

        if ($error != null) {
            return false;
        }
        return $ret['key'];
    }
    /**
     * 删除七牛云的旧图片
     * @param $oldKey
     */
    public function deleteOldKey($oldKey) {
        $bucketManager = new BucketManager($this->auth);
        return $bucketManager->delete($this->_bucket,$oldKey);
    }

    /**
     * 获取七牛云上传凭证
     * @param $key
     * @param $transCode
     * @param $ext
     * @param int $notify
     * @return mixed
     */
    public function getUpToken ($key, $transCode, $ext, $notify = self::TRANS_CODE_URL_LEARN) {
        $policy = [];
        $notifyUrl = self::NOTIFY_URL[$notify];
        if ($transCode !== $ext) {
            //需要转码
            switch ($transCode) {
                case 'mp4' :
                    $saveKey = \Qiniu\base64_urlSafeEncode($this->_bucket.':transcode_'.$key.'.mp4');
                    $avThumbMp4Fop = "avthumb/mp4/ab/128k/ar/22050/acodec/libfaac/r/30/vb/300k/vcodec/libx264/s/320x240/autoscale/1/stripmeta/0|saveas/".$saveKey;
                    $policy = [
                        'persistentOps' => $avThumbMp4Fop,
                        'persistentPipeline' => $this->_transCodeQueue,
                        'persistentNotifyUrl' => $notifyUrl,
                    ];

                    break;
                case 'mp3' :
                    $saveKey = \Qiniu\base64_urlSafeEncode($this->_bucket.':transcode_'.$key.'.mp3');
                    $avThumbMp3Fop = "avthumb/mp3/ab/128k/ar/44100/acodec/libmp3lame|saveas/".$saveKey;
                    $policy = [
                        'persistentOps' => $avThumbMp3Fop,
                        'persistentPipeline' => $this->_transCodeQueue,
                        'persistentNotifyUrl' => $notifyUrl,
                    ];
                    break;
                default :
                    break;
            }

        }
        $auth = $this->auth;
        $upToken = $auth->uploadToken($this->_bucket, null, 3600, $policy, true);
        return $upToken;
    }
}
